<?php

namespace ExAdmin\ui\component\detail;

use ExAdmin\ui\component\Component;
use ExAdmin\ui\component\grid\descriptions\Descriptions;
use ExAdmin\ui\component\grid\descriptions\DescriptionsItem;
use ExAdmin\ui\support\Arr;

/**
 * Class Detail
 * @method static $this create($data = [],\Closure $closure = null) 创建
 */
class Detail extends Descriptions
{
    /**
     * @var array
     */
    protected $item = [];
    /**
     * 数据源
     * @var array
     */
    protected $data = [];

    protected $exec;

    public function __construct($data = [],\Closure $closure = null)
    {
        if($data instanceof \Closure){
            $closure = $data;
        }
        $this->exec = $closure;
        $this->data = $data;
        $this->attr('data',$data);
       // $this->column(['xxl'=> 4, 'xl'=> 3, 'lg'=> 3, 'md'=> 3, 'sm'=> 2, 'xs'=> 1]);
        parent::__construct();
    }
    /**
     * 设置源
     * @param array $data
     */
    public function source($data){
        $this->data = $data;
    }
    /**
     * 添加一个item
     * @param string $field 字段
     * @param string|Component $label 内容的描述
     * @return Item
     */
    public function item($field = null, $label = null)
    {
        $item = new Item($field,$label,$this->data);
        $this->item[] = $item;
        return $item;
    }
    public function getItems(){
        return $this->item;
    }
    /**
     * 获取数据
     * @param string|null $field 字段
     * @return array|mixed
     */
    public function getData(string $field = null)
    {
        if (is_null($field)) {
            return $this->data;
        }
        return Arr::get($this->data, $field);
    }
    public function collectColumns(\Closure $closure)
    {
        $offset = count($this->item);
        call_user_func($closure, $this);
        $items = array_slice($this->item, $offset);
        $this->item = array_slice($this->item, 0, $offset);
        return $items;
    }
    public function jsonSerialize()
    {
        if($this->exec){
            call_user_func($this->exec,$this);
        }
        
        $this->content($this->item);
        return parent::jsonSerialize(); // TODO: Change the autogenerated stub
    }
}
